package com.xuanrui.commons.wechat;




import com.xuanrui.commons.HttpTookit;
import com.xuanrui.commons.NumberUtil;
import com.xuanrui.commons.YXDate;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Created by 阿丰 on 2019/3/4.
 */
public class WXJSSDKUtil {
//    @Value("${wx.url}")
    private static String wxUrl="fashionwap.facexxxx.cn";
//    @Value("${wx.appId}")
    private static String wxAppId="wx6b0758d788b94c77";
//    @Value("${wx.appSecret}")
    private static String wxAppSecret="2534d6bb3f83eee7d5c31f079c8f40fe";



    private static String WX_ACCESS_TOKEN = "";//微信公众号token
    private static String JSAPI_TICKET = "";//jsapi_ticket是公众号


    private static Date TOKEN_START_TIME;//上次获取token时间
    private static Date JSAPI_TICKET_START_TIME;//上次获取tiket时间

    private static int TOKEN_EXPIRES_IN = 7200;
    private static int TICKET_EXPIRES_IN = 7200;

    /**
     * 得到wxaccestoken
     *
     * @return
     */
    public static String getWxAccessToken() {


        if (WX_ACCESS_TOKEN == null || "".equals(WX_ACCESS_TOKEN)) {

            WX_ACCESS_TOKEN = getAccessToken();
            TOKEN_START_TIME = new Date();
            return WX_ACCESS_TOKEN;
        }


        //说明已过期
        if (YXDate.addSeconds(TOKEN_START_TIME, TOKEN_EXPIRES_IN).before(new Date())) {

            WX_ACCESS_TOKEN = getAccessToken();
            TOKEN_START_TIME = new Date();

        }

        return WX_ACCESS_TOKEN;
    }


    /**
     * 签名
     *
     * @return
     */
    public static Map<String, String> getSignPackage(String url) {


        if(url=="" || "".equals(url))

            url = wxUrl;

        return sign(getJsapi(), url);
    }







    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String appId = wxAppId;
        String appSecret = wxAppSecret;


        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("appId", appId);
        ret.put("appSecret", appSecret);
        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


    public static String getJsapi() {


        if (JSAPI_TICKET == null || "".equals(JSAPI_TICKET)) {

            JSAPI_TICKET = getJsapi(getWxAccessToken());
            JSAPI_TICKET_START_TIME = new Date();
            return JSAPI_TICKET;
        }

        //说明已过期
        if (YXDate.addSeconds(JSAPI_TICKET_START_TIME, TICKET_EXPIRES_IN).before(new Date())) {

            JSAPI_TICKET = getJsapi(getWxAccessToken());
            JSAPI_TICKET_START_TIME = new Date();

        }

        return JSAPI_TICKET;


    }


    /**
     * 获取微信access_token
     *
     * @return
     */
    private static String getAccessToken() {


        String appId = wxAppId;
        String appSecret = wxAppSecret;




        String url = "https://api.weixin.qq.com/cgi-bin/token" +
                "?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;

        String resJson = HttpTookit.doGet(url, null);

        JSONObject json = null;
        String access_token = "";
        try {
            json = new JSONObject(resJson);
            access_token = json.getString("access_token");
            TOKEN_EXPIRES_IN = NumberUtil.parseInt(json.getInt("expires_in"), 7200);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.print("token:"+access_token);

        return access_token;
    }


    /**
     * @param access_token
     * @return {
     * "errcode":0,
     * "errmsg":"ok",
     * "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
     * "expires_in":7200
     * }
     */
    private static String getJsapi(String access_token) {


        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
        String resJson = HttpTookit.doGet(url, null);
        System.out.println("accessToken:"+resJson);
        JSONObject json = null;
        try {


            System.out.println("jsapi:"+resJson);

            json = new JSONObject(resJson);


            TICKET_EXPIRES_IN = NumberUtil.parseInt(json.getInt("expires_in"), 7200);

            return json.getString("ticket");
        } catch (JSONException e) {
            e.printStackTrace();

        }

        return "";
    }

}
